package com.dq.controller.api.merchant.workbench.finance;

import com.dq.exception.customException.AdminException;
import com.dq.controller.in.PayrollRecordQuery;
import com.dq.controller.in.RewardQuery;
import com.dq.controller.api.merchant.in.query.RoyalRecordQuery;
import com.dq.vo.Vo;
import com.dq.vo.baseVo.VO;

import com.dq.domain.orders.UserOrder;
import com.dq.domain.orders.info.OrderInfo;
import com.dq.domain.org.Org;
import com.dq.domain.record.PayrollRecord;
import com.dq.domain.record.RoyaltyRecord;
import com.dq.domain.reward.Reward;
import com.dq.domain.sys.section.SysSection;
import com.dq.domain.setup.WorkRoyaltySet;
import com.dq.domain.sys.user.user.StaffUser;
import com.dq.domain.sys.user.user.base.SysUser;
import com.dq.service.AllService;
import com.dq.utils.PageableUtil;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @author liuhui
 * @date 2019/11/28 0028 09:47:42
 */
@RestController
@RequestMapping("/api/merchant/workbench/finance")
@Api(description = "门店财务")
public class OrgFinanceController extends AllService {

    @GetMapping("/workRoyaltySet/list/{page}/{size}")
    @ApiOperation("提成比例列表")
    public Vo workRoyaltySerList(@PathVariable Integer page,@PathVariable Integer size){
        Page<WorkRoyaltySet> workRoyaltySetPages = workRoyaltySetRepository.findByOrgAndDeletedFalse(loginTemplate.getOrg(), PageableUtil.get(page,size));
        Long totalCount = workRoyaltySetRepository.countByOrgAndDeletedFalse(loginTemplate.getOrg());
        List<WorkRoyaltySet.RoyaltListVo> royaltListVoList = new ArrayList<>();
        workRoyaltySetPages.getContent().forEach(workRoyaltySet -> {royaltListVoList.add(workRoyaltySet.toRoyaltListVo());});
        PageInfo pageInfo = new PageInfo(royaltListVoList);
        pageInfo.setTotal(totalCount);
        return new Vo(pageInfo);
    }

    @PostMapping("/workRoyaltySet/add/{orgOptionId}")
    @ApiOperation("提成比例添加")
    public Vo workRoyaltySetAdd(@PathVariable Long orgOptionId,@RequestBody WorkRoyaltySet workRoyaltySetAdd)throws AdminException {
        if(null==workRoyaltySetAdd.getLowerLimitPrice() || null==workRoyaltySetAdd.getTopLimitPrice() || null==workRoyaltySetAdd.getProportion()){throw new AdminException("缺少必要的请求参数");}
        SysSection sysDept = shiroService.getDept();
        if(sysDept == null){
            throw new AdminException("用户门店信息异常");
        }
        workRoyaltyService.add(sysDept.getId(),orgOptionId,workRoyaltySetAdd);
        return new Vo(HttpStatus.OK);
    }

    @PostMapping("/workRoyaltySet/edit/{id}")
    @ApiOperation("提成比例修改")
    public Vo workRoyaltySetEdit(@PathVariable Long id,@RequestBody  WorkRoyaltySet workRoyaltySetEdit)throws AdminException{
        WorkRoyaltySet workRoyaltySet = dao.get(WorkRoyaltySet.class,id);
        SysSection sysDept = shiroService.getDept();
        if(sysDept == null){
            throw new AdminException("用户门店信息异常");
        }
        return workRoyaltyService.edit(sysDept.getId(),workRoyaltySet.getOrgPosition().getId(),workRoyaltySetEdit);
    }

    @PostMapping("/workRoyaltySet/delete/{id}")
    @ApiOperation("提成比例删除")
    public Vo workRoyaltySetDelete(@PathVariable Long id)throws AdminException{
        return workRoyaltyService.delete(id);
    }

    @GetMapping("/baseSalary/list/{page}/{size}")
    @ApiOperation("员工基本工资列表")
    public Vo baseSalaryList(@PathVariable Integer page,@PathVariable Integer size)throws AdminException{
        /*Org org = loginTemplate.getOrg();
        Page<StaffUser> staffUserPages = staffUserRepository.findBySectionAndStaffUserStatusAndDeletedFalse(org, StaffUser.StaffUserStatus.on,PageableUtil.get(page,size));
        Long totalCount = staffUserRepository.countBySectionAndStaffUserStatusAndDeletedFalse(org, StaffUser.StaffUserStatus.on);
        List<StaffUser.StaffUserDetailVo> staffUserDetailVos = new ArrayList<>();
        staffUserPages.getContent().forEach(staffUser -> {staffUserDetailVos.add(staffUser.toStaffUserDetailVo());});
        PageInfo pageInfo = new PageInfo(staffUserDetailVos);
        pageInfo.setTotal(totalCount);
        return new Vo(pageInfo);*/
        return null;
    }

    @PostMapping("/baseSalary/add/{cardNo}/{baseSalary}")
    @ApiOperation("基本工资添加")
    public Vo baseSalaryAdd(@PathVariable @ApiParam("工号") String cardNo, @PathVariable  BigDecimal baseSalary)throws AdminException{
        /*StaffUser staffUser = staffUserRepository.findByCardNoAndStaffUserStatus(cardNo, StaffUser.StaffUserStatus.on);
        if(null==staffUser){throw new AdminException("员工信息不存在或者已离职");}
        staffUser.setBaseSalary(baseSalary);
        staffUserRepository.save(staffUser);
        basePaySetRecordService.add(baseSalary,staffUser.getSection().getId(),staffUser.getId());*/
        return new Vo(HttpStatus.OK);
    }

    @PostMapping("/baseSalary/edit/{id}/{baseSalary}")
    @ApiOperation("基本工资修改")
    public Vo baseSalaryEdit(@PathVariable @ApiParam("用户id") Long id,@PathVariable  BigDecimal baseSalary)throws AdminException{
        StaffUser staffUser = dao.get(StaffUser.class,id);
        if(null==staffUser){throw new AdminException("员工信息不存在或者已离职");}
        staffUser.setBaseSalary(baseSalary);
        staffUserRepository.save(staffUser);
        basePaySetRecordService.add(baseSalary,staffUser.getSection().getId(),staffUser.getId());
        return new Vo(HttpStatus.OK);
    }

    @PostMapping("/baseSalary/delete/{id}")
    @ApiOperation("基本工资删除")
    public Vo baseSalaryDelete(@PathVariable @ApiParam("用户id") Long id)throws AdminException{
        return baseSalaryEdit(id,BigDecimal.ZERO);
    }

    @PostMapping("/royaltyRecord/list")
    @ApiOperation("提成记录")
    public Vo royaltyRecordList(@RequestBody RoyalRecordQuery royalRecordQuery)throws AdminException{
        if(null==royalRecordQuery.getPage() || null==royalRecordQuery.getSize()){throw new AdminException("缺少必要的请求参数");}
        Org org = loginTemplate.getOrg();
        List<RoyaltyRecord> royaltyRecordList = royaltyRecordService.findByWhere(royalRecordQuery,org);
        Long totalCount = royaltyRecordService.countByWhere(royalRecordQuery,org);
        List<RoyaltyRecord.RoyaltyRecordListVo> royaltyRecordListVos = new ArrayList<>();
        royaltyRecordList.forEach(royaltyRecord -> {royaltyRecordListVos.add(royaltyRecord.toRoyaltyRecordListVo());});
        PageInfo pageInfo = new PageInfo(royaltyRecordListVos);
        pageInfo.setTotal(totalCount);
        return new Vo(pageInfo);
    }

    @GetMapping("/royalRecord/detail/{id}")
    @ApiOperation("提成记录商品详情")
    public Vo royalRecordDetail(@PathVariable @ApiParam("提成关联订单id") Long id)throws AdminException{
        UserOrder userOrder = dao.get(UserOrder.class,id);
        if(null==userOrder){throw new AdminException("该订单不存在");}
        List<OrderInfo> orderInfoList = orderInfoRepository.findByOrders(userOrder);
        List<OrderInfo.OrgOrderInfoVo> orgOrderInfoVos = new ArrayList<>();
        orderInfoList.forEach(orderInfo -> {orgOrderInfoVos.add(orderInfo.toOrgOrderInfoVo());});
        PageInfo pageInfo = new PageInfo(orgOrderInfoVos);
        return new Vo(pageInfo);
    }

    @PostMapping("/reward/list")
    @ApiOperation("专项/随机奖励列表")
    public Vo rewardList(@RequestBody RewardQuery rewardQuery)throws AdminException{
        if(null==rewardQuery.getPage() || null==rewardQuery){throw new AdminException("缺少必要的请求参数");}
        Org org = loginTemplate.getOrg();
        List<Reward> rewardList = rewardService.findByWhere(rewardQuery,org);
        Long totalCount = rewardService.countByWhere(rewardQuery,org);
        PageInfo pageInfo = new PageInfo((List<Reward.Vo>)VO.toVOCollection(rewardList));
        pageInfo.setTotal(totalCount);
        return new Vo(pageInfo);
    }

    @PostMapping("/reward/add/{cardNo}")
    @ApiOperation("专项/随机奖励添加")
    public Vo rewardAdd(@PathVariable String cardNo,@RequestBody Reward rewardAdd)throws AdminException{
        /*StaffUser staffUser = staffUserRepository.findByCardNoAndStaffUserStatus(cardNo, StaffUser.StaffUserStatus.on);
        if(null==staffUser){throw new AdminException("该员工不存在或已离职");}
        rewardAdd.setStaffUser(staffUser);
        rewardAdd.setOrg(loginTemplate.getOrg());
        rewardRepository.save(rewardAdd);*/
        return new Vo(HttpStatus.OK);
    }

    @PostMapping("/payrollRecord/list")
    @ApiOperation("工资单/记录列表")
    public Vo payrollRecordList(@RequestBody PayrollRecordQuery payrollRecordQuery)throws AdminException{
        if(null==payrollRecordQuery.getPage() || null==payrollRecordQuery.getSize()){throw new AdminException("缺少必要的请求参数");}
        Org org = null;
        if(payrollRecordQuery.getOrgId() != null){
            org = dao.get(Org.class,payrollRecordQuery.getOrgId());
        }
        return payrollRecordService.findByWhere(payrollRecordQuery,org);
    }

    @GetMapping("/payrollRecord/detail/{id}")
    @ApiOperation("工资单详情")
    public Vo payrollRecordDetail(@PathVariable Long id)throws AdminException{
        PayrollRecord payrollRecord= dao.get(PayrollRecord.class,id);
        if(null==payrollRecord){throw new AdminException("该工资单信息不存在");}
        return new Vo(payrollRecord.toOrgPayrollRecordDetailVo());
    }

    @PostMapping("/payrollRecord/check")
    @ApiOperation("工资单审批")
    public Vo payrollRecordCheck(@RequestBody List<Long> longs){
        List<PayrollRecord> payrollRecordList = payrollRecordRepository.findAllById(longs);
        if(null!=payrollRecordList || payrollRecordList.size()!=0){
            List<PayrollRecord> payrollRecords = new ArrayList<>();
            payrollRecordList.forEach(payrollRecord -> {
                payrollRecord.setPayrollStatus(PayrollRecord.PayrollStatus.waitConfirm);
                payrollRecords.add(payrollRecord);
            });
            if(payrollRecords.size()>0){
                payrollRecordRepository.saveAll(payrollRecords);
            }
        }
        return new Vo(HttpStatus.OK);
    }

    @PostMapping("/confim/{id}")
    @ApiOperation("技师确认工资单")
    public Vo confim(@PathVariable @ApiParam("工资单id") Long id)throws AdminException{
        SysUser sysUser = shiroService.getUser();
        if(sysUser == null){
            throw new AdminException("请先登陆");
        }
        PayrollRecord payrollRecord = dao.get(PayrollRecord.class,id);
        payrollRecord.setPayrollStatus(PayrollRecord.PayrollStatus.ConfirmSuccess);
        payrollRecordRepository.save(payrollRecord);
        return new Vo(HttpStatus.OK);
    }

}
